package org.hit.burkun.umls;

import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import org.hit.burkun.db.DBHelper;
import org.hit.burkun.entities.Entity;

public class HpClinvarUmls extends BaseMapper {
	// SELECT concept_id,source_id FROM biosearch.clinvar_term_disease;
	private MapidsUmlsDump mapDbh;
	private String mapPath = "hp=>clinvar=>umls";
	private Entity.TYPE type = Entity.TYPE.HP_ONTOLOGY;
	private String whereCondition = " where concept_id not like 'CN%' and concept_id is not null and source_id like 'HP:%'";

	public HpClinvarUmls(DBHelper dbh, String tbName, MapidsUmlsDump mapDbh) {
		super(dbh, tbName);
		this.mapDbh = mapDbh;
	}

	@Override
	public void process(Map<String, Set<String>> data) {
		// 保存到数据库
		mapDbh.updateUmlsByMapedData(type, data, mapPath);
	}

	public void quickMap() {
		Collection<String> unMaped = getAllUnmapedHpTerm();
		Map<String, Set<String>> clinvarMap = getAllClinvarCUI2HPO();
		Map<String, Set<String>> finalMap = new HashMap<>();
		for (String hpid : unMaped) {
			if (clinvarMap.containsKey(hpid)) {
				if (finalMap.containsKey(hpid)) {
					finalMap.get(hpid).addAll(clinvarMap.get(hpid));
				} else {
					Set<String> set = new HashSet<>();
					set.addAll(clinvarMap.get(hpid));
					;
					finalMap.put(hpid, set);
				}
			}
		}
		process(finalMap);
	}

	private Map<String, Set<String>> getAllClinvarCUI2HPO() {
		Collection<String[]> res = dbh.queryData(
				"select concept_id, source_id from " + tbName + whereCondition,
				2);
		return getMapedData(res);
	}

	private Collection<String> getAllUnmapedHpTerm() {
		String sqlStr = "select db_id from map_umls_ids where db_type = '"
				+ type.getTag() + "'" + " and is_mapped = 0";
		DBHelper dbh = DBHelper.getServerData();
		dbh.connectionDB();
		System.out.println(sqlStr);
		Collection<String> res = dbh.queryData(sqlStr);
		dbh.disconnection();
		return res;
	}

}
